<template>
	<view class="container">
		<!-- 搜索栏 -->
		<view class="search-box">
			<view class="search-input" @click="onSearchClick">
				<u-icon name="search" size="30" color="#909399"></u-icon>
				<text class="search-text">请搜索您想要的商品</text>
			</view>
		</view>

		<!-- 分类内容 -->
		<view class="category-content">
			<!-- 左侧一级分类 -->
			<scroll-view scroll-y class="category-menu">
				<view
					v-for="(item, index) in categoryList"
					:key="item.id"
					class="category-item"
					:class="{active: currentCategoryId === item.id}"
					@click="switchCategory(item.id)"
				>
					<text>{{item.name}}</text>
				</view>
			</scroll-view>

			<!-- 右侧商品列表 -->
			<view class="product-side">
				<!-- 筛选栏 -->
				<view class="filter-bar">
					<view
						class="filter-item"
						:class="{active: sortType === 'id'}"
						@click="changeSort('id')"
					>
						<text>综合</text>
					</view>

          <view
              class="filter-item"
              :class="{active: sortType === 'sales'}"
              @click="changeSort('sales')"
          >
            <view class="price-sort">
              <text :class="{active: sortType === 'sales'}">销量</text>
              <view class="sort-icon">
                <u-icon
                    name="arrow-up-fill"
                    size="18"
                    :color="sortType === 'sales' && sortOrder === 'asc' ? '#2979ff' : '#c0c4cc'"
                ></u-icon>
                <u-icon
                    name="arrow-down-fill"
                    size="18"
                    :color="sortType === 'sales' && sortOrder === 'desc' ? '#2979ff' : '#c0c4cc'"
                ></u-icon>
              </view>
            </view>
          </view>
          <view
              class="filter-item"
              :class="{active: sortType === 'price'}"
              @click="changeSort('price')"
          >
            <view class="price-sort">
              <text :class="{active: sortType === 'price'}">价格</text>
              <view class="sort-icon">
                <u-icon
                    name="arrow-up-fill"
                    size="18"
                    :color="sortType === 'price' && sortOrder === 'asc' ? '#2979ff' : '#c0c4cc'"
                ></u-icon>
                <u-icon
                    name="arrow-down-fill"
                    size="18"
                    :color="sortType === 'price' && sortOrder === 'desc' ? '#2979ff' : '#c0c4cc'"
                ></u-icon>
              </view>
            </view>
          </view>
          <view
              class="filter-item"
              :class="{active: sortType === 'create_time'}"
              @click="changeSort('create_time')"
          >
            <view class="price-sort">
              <text :class="{active: sortType === 'create_time'}">时间</text>
              <view class="sort-icon">
                <u-icon
                    name="arrow-up-fill"
                    size="18"
                    :color="sortType === 'create_time' && sortOrder === 'asc' ? '#2979ff' : '#c0c4cc'"
                ></u-icon>
                <u-icon
                    name="arrow-down-fill"
                    size="18"
                    :color="sortType === 'create_time' && sortOrder === 'desc' ? '#2979ff' : '#c0c4cc'"
                ></u-icon>
              </view>
            </view>
          </view>
				</view>

				<scroll-view 
					scroll-y 
					class="product-container"
					@scrolltolower="loadMore"
					refresher-enabled
					:refresher-triggered="refreshing"
					@refresherrefresh="onRefresh"
				>
					<view v-if="loading && page === 1" class="loading-box">
						<u-loading mode="circle" size="36"></u-loading>
						<text class="loading-text">加载中...</text>
					</view>

					<view v-else-if="productList.length === 0" class="empty-box">
						<u-empty mode="list" icon="http://cdn.uviewui.com/uview/empty/list.png"></u-empty>
						<text class="empty-text">暂无商品</text>
					</view>

					<view v-else class="product-grid">
						<view
							v-for="item in productList"
							:key="item.id"
							class="product-item"
							@click="goToDetail(item.id)"
						>
							<image class="product-image" :src="item.thumbnail || '/static/images/default-product.png'" mode="aspectFill"></image>
							<view class="product-info">
								<text class="product-name">{{item.name}}</text>
								<view class="product-price-box">
									<text class="product-price">¥{{item.price}}</text>
									<text v-if="item.support_points" class="product-points">{{item.points_price}}积分</text>
								</view>
								<view class="product-meta">
									<text class="product-sales">已售{{item.sales}}件</text>
									<view class="buy-btn">购买</view>
								</view>
							</view>
						</view>
					</view>

					<!-- 加载更多 -->
					<view v-if="loading && page > 1" class="loading-more">
						<u-loading mode="circle" size="24"></u-loading>
						<text>加载中...</text>
					</view>

					<view v-if="!loading && !hasMore" class="no-more">
						<text>没有更多了</text>
					</view>
				</scroll-view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				categoryList: [], // 一级分类列表
        currentCategoryId: 0, // 当前选中的一级分类索引
				loading: false, // 加载状态
				productList: [], // 商品列表
				page: 1, // 当前页码
				pageSize: 10, // 每页数量
				hasMore: true, // 是否有更多数据
				refreshing: false, // 下拉刷新状态
				sortType: 'id', // 排序类型：id(综合)、sales(销量)、price(价格)、newest(上新)
				sortOrder: 'desc' // 排序方向：asc(升序)、desc(降序)
			}
		},
		onLoad() {
			this.getCategoryTree();
		},
		methods: {
			// 获取分类树
			async getCategoryTree() {
				try {
					this.loading = true;
					const res = await this.$api.getOfficeCategoryTree({ type: 1});
          if (res.length) {
            this.categoryList = res.map(item => ({
              id: item.id,
              name: item.name
            }));
            // 设置当前选中的分类为第一个分类
            this.currentCategoryId = res[0].id
            // 使用第一个分类的ID加载商品
            await this.loadProductList();
          }
				} catch (error) {
					console.error('获取分类出错', error);
					uni.showToast({
						title: '网络异常，请稍后重试',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},

			// 切换一级分类
			switchCategory(id) {
				if (this.currentCategoryId === id) return;
				this.currentCategoryId = id;
				this.page = 1;
				this.hasMore = true;
				this.productList = [];
				this.loadProductList();
			},
			
			// 切换排序方式
			changeSort(type) {
				if (type === 'id') {
          this.sortOrder = ''
        } else {
          if (this.sortType !== type) {
            this.sortOrder = 'asc'
          } else {
            if (this.sortOrder === 'asc') {
              this.sortOrder = 'desc'
            } else {
              this.sortOrder = 'asc'
            }
          }
        }
        this.sortType = type
				// 重置分页并重新加载
				this.page = 1;
				this.hasMore = true;
				this.productList = [];
				this.loadProductList();
			},
			
			// 加载商品列表
			async loadProductList() {
				try {
					this.loading = true;

					// 构建请求参数
					const params = {
						pageNo: this.page,
						pageSize: this.pageSize,
						categoryId: this.currentCategoryId
					};

					// 添加排序参数
					if (this.sortType === 'id') {
						params.sort = '';
						params.order = 'desc';
					} else if (this.sortType === 'sales') {
						params.sort = 'sales';
						params.order = 'desc';
					} else if (this.sortType === 'price') {
						params.sort = 'price';
						params.order = this.sortOrder;
					} else if (this.sortType === 'newest') {
						params.sort = 'create_time';
						params.order = 'desc';
					}

					console.log('加载商品列表，参数：', params);

					// 发起请求
					const res = await this.$api.getOfficeProductList(params);
					console.log('商品列表响应：', res);

					// 处理响应数据
					if (this.page === 1) {
						this.productList = res.rows || [];
					} else {
						this.productList = [...this.productList, ...(res.rows || [])];
					}

					// 更新分页信息
					this.hasMore = (res.rows || []).length === this.pageSize;
					
				} catch (error) {
					console.error('获取商品列表出错', error);
					uni.showToast({
						title: '网络异常，请稍后重试',
						icon: 'none'
					});
				} finally {
					this.loading = false;
					this.refreshing = false;
				}
			},
			
			// 加载更多
			loadMore() {
				if (!this.loading && this.hasMore) {
					this.page++;
					this.loadProductList();
				}
			},
			
			// 下拉刷新
			onRefresh() {
				this.refreshing = true;
				this.page = 1;
				this.hasMore = true;
				this.loadProductList();
			},
			
			// 点击搜索框
			onSearchClick() {
				uni.navigateTo({
					url: '/pages/officeShop/product/search'
				});
			},
			
			// 跳转到商品详情
			goToDetail(id) {
				uni.navigateTo({
					url: `/pages/officeShop/product/detail?id=${id}`
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
.container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #f5f5f5;
}

.search-box {
	padding: 20rpx 30rpx;
	background-color: #ffffff;
}

.search-input {
	display: flex;
	align-items: center;
	background-color: #f5f5f5;
	border-radius: 50rpx;
	padding: 15rpx 30rpx;
}

.search-text {
	margin-left: 10rpx;
	color: #909399;
	font-size: 28rpx;
}

.category-content {
	display: flex;
	flex: 1;
	overflow: hidden;
}

.category-menu {
	width: 180rpx;
	height: 100%;
	background-color: #f6f6f6;
}

.category-item {
	height: 100rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 28rpx;
	color: #333;
	position: relative;
	padding: 0 20rpx;
	text-align: center;
}

.category-item.active {
	background-color: #ffffff;
	color: #2979ff;
	font-weight: bold;
}

.category-item.active::before {
	content: '';
	position: absolute;
	left: 0;
	top: 50%;
	transform: translateY(-50%);
	height: 40rpx;
	width: 6rpx;
	background-color: #2979ff;
}

.product-side {
	flex: 1;
	display: flex;
	flex-direction: column;
	height: 100%;
	background-color: #ffffff;
}

.filter-bar {
  flex-shrink: 0;
	display: flex;
	align-items: center;
	height: 90rpx;
	background-color: #ffffff;
	border-bottom: 1rpx solid #f0f0f0;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	position: sticky;
	top: 0;
	z-index: 10;
}

.filter-item {
	flex: 1;
	display: flex;
	justify-content: center;
	align-items: center;
	height: 100%;
	font-size: 28rpx;
	color: #666666;
	position: relative;
	transition: all 0.2s;
}

.filter-item.active {
	color: #2979ff;
	font-weight: bold;
}

.filter-item.active::after {
	content: '';
	position: absolute;
	bottom: 0;
	left: 50%;
	transform: translateX(-50%);
	width: 40rpx;
	height: 4rpx;
	background-color: #2979ff;
	border-radius: 2rpx;
}

.filter-item:active {
	background-color: #f9f9f9;
}

.price-sort {
	display: flex;
	align-items: center;
}

.sort-icon {
	display: flex;
	flex-direction: column;
	margin-left: 8rpx;
	height: 30rpx;
}

.product-container {
	flex: 1;
	height: 100%;
	padding: 20rpx;
}

.loading-box, .empty-box {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 60rpx 0;
}

.loading-text, .empty-text {
	margin-top: 20rpx;
	font-size: 28rpx;
	color: #909399;
}

.product-grid {
	display: flex;
	flex-direction: column;
}

.product-item {
	display: flex;
	padding: 20rpx 0;
	border-bottom: 1px solid #f5f5f5;
}

.product-image {
	width: 180rpx;
	height: 180rpx;
	border-radius: 10rpx;
	margin-right: 20rpx;
}

.product-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
}

.product-name {
	font-size: 28rpx;
	color: #333;
	line-height: 1.4;
	margin-bottom: 10rpx;
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 2;
	overflow: hidden;
}

.product-price-box {
	display: flex;
	align-items: center;
	margin-bottom: 10rpx;
}

.product-price {
	font-size: 32rpx;
	color: #ff5500;
	font-weight: bold;
}

.product-points {
	font-size: 24rpx;
	color: #ff5500;
	margin-left: 10rpx;
}

.product-meta {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.product-sales {
	font-size: 24rpx;
	color: #909399;
}

.buy-btn {
	background-color: #2979ff;
	color: #ffffff;
	font-size: 24rpx;
	padding: 6rpx 20rpx;
	border-radius: 30rpx;
}

.loading-more, .no-more {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 30rpx 0;
	font-size: 24rpx;
	color: #909399;
}

.loading-more text {
	margin-left: 10rpx;
}
</style>
